package com.jiawa.train.member.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.train.common.context.LoginMemberContext;
import com.jiawa.train.common.exception.BusinessException;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import com.jiawa.train.member.domain.Passenger;
import com.jiawa.train.member.domain.PassengerExample;
import com.jiawa.train.member.mapper.PassengerMapper;
import com.jiawa.train.member.req.PassengerQueryReq;
import com.jiawa.train.member.req.PassengerSaveReq;
import com.jiawa.train.member.resp.PassengerQueryResp;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PassengerService {

    private static final Logger LOG = LoggerFactory.getLogger(PassengerService.class);

    @Resource
    private PassengerMapper passengerMapper;


    /**
     * 校验身份证号码唯一性
     *
     * @param idCard      身份证号码
     * @param memberId    会员ID
     * @param passengerId 乘客ID（用于更新时排除自己）
     */


    private void verifyIdCardUnique(String idCard, Long memberId, Long passengerId) {
        PassengerExample passengerExample = new PassengerExample();
        PassengerExample.Criteria criteria = passengerExample.createCriteria();
        criteria.andMemberIdEqualTo(memberId).andIdCardEqualTo(idCard);

        // 如果是更新，排除自己
        if (ObjectUtil.isNotNull(passengerId)) {
            criteria.andIdNotEqualTo(passengerId);
        }

        long count = passengerMapper.countByExample(passengerExample);
        if (count > 0) {
            throw new BusinessException(BusinessExceptionEnum.PASSENGER_ID_CARD_EXIST);
        }
    }


    public Passenger save(PassengerSaveReq req) {
        Long memberId = LoginMemberContext.getId();

        verifyIdCardUnique(req.getIdCard(), memberId, req.getId());

        Passenger passenger = BeanUtil.copyProperties(req, Passenger.class);
        DateTime now = DateTime.now();
        passenger.setUpdateTime(now);
        passenger.setMemberId(memberId);

        if (ObjectUtil.isNotNull(req.getId())) {
            passengerMapper.updateByPrimaryKeySelective(passenger);
        } else {
            passenger.setId(SnowUtil.getSnowflakeNextId());
            passenger.setCreateTime(now);
            passengerMapper.insert(passenger);
        }
        return passenger;
    }


    public void delete(Long id) {
        Passenger passenger = passengerMapper.selectByPrimaryKey(id);
        if (passenger == null) {
            throw new BusinessException(BusinessExceptionEnum.PASSENGER_NOT_EXIST);
        }
        passengerMapper.deleteByPrimaryKey(id);
    }

    public PageResp<PassengerQueryResp> queryList(PassengerQueryReq req) {
        PassengerExample passengerExample = new PassengerExample();
        PassengerExample.Criteria criteria = passengerExample.createCriteria();

        Long memberId = req.getMemberId();
        if (ObjectUtil.isNotNull(memberId)) {
            criteria.andMemberIdEqualTo(memberId);
        }

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Passenger> passengerList = passengerMapper.selectByExample(passengerExample);

        PageInfo<Passenger> pageInfo = new PageInfo<>(passengerList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<PassengerQueryResp> list = BeanUtil.copyToList(passengerList, PassengerQueryResp.class);


        PageResp<PassengerQueryResp> pageResp = new PageResp<>();
        pageResp.setList(list);
        pageResp.setTotal(pageInfo.getTotal());
        return pageResp;
    }

}
